import axios from 'axios';
import router from '@/router';
import { useSysConfigStore } from '@/stores/sysConfig'

const service = axios.create({
    baseURL: '/api', // 基础URL，可以在.env文件中配置
    // baseURL: '/api', // 基础URL，可以在.env文件中配置
    timeout: 10000 // 请求超时时间
});

service.interceptors.request.use(
    config => {
        // 在请求发送之前做一些处理，比如添加token
        const token = localStorage.getItem('pangu-authorization-token');
        if (token && !config.url.endsWith('/login') && !config.url.endsWith('/captcha')) {
            config.headers['Authorization'] = 'Bearer ' + token;
        }
        return config;
    },
    error => {
        // 处理请求错误
        console.error(error);
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 处理二进制响应（如文件下载）
        if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
            return response.data;
        }
        // 200 成功直接返回，501至505 登录问题直接返回，由登录页面进行验证码刷新处理
        if (response.data.code === 200 && 501 >= response.data.code <= 505) {
            return response.data
        } else if (response.data.code === 401) {
            localStorage.removeItem('pangu-authorization-token')
            const sysConfig = useSysConfigStore()
            sysConfig.routerList = []
            router.push('/login')
        } else {
            ElMessage.error(response.data.msg)
            return Promise.reject(new Error(response.data.msg))
        }
    },
    error => {
        return Promise.reject(error);
    }
);

export function get(url, params) {
    return service({
        url: url,
        method: 'get',
        params: params
    });
}

export function post(url, data) {
    return service({
        url: url,
        method: 'post',
        data: data
    });
}

export function put(url, data) {
    return service({
        url: url,
        method: 'put',
        data: data
    });
}

export function del(url, params) {
    return service({
        url: url,
        method: 'delete',
        params: params
    });
}

export function postFile(url, data) {
    return service({
        url: url,
        method: 'post',
        data: data,
        headers: {
            'Content-Type': 'multipart/form-data',
        }
    })
}

export default service;